﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Net;
using System.IO;
using System.Drawing.Imaging;
using System.Threading;

namespace FotoButh
{
    class SnatchImage
    {
        public event Action<object, Image> GotImage;
        public Uri ImageUri { get; set; }

        public SnatchImage()
        { }

        private void FireGotImage(Image image)
        {
            if (GotImage != null)
                GotImage(this, image);
        }

        private string ImageFilename
        {
            get
            {
                string text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "images");
                if (!Directory.Exists(text))
                {
                    Directory.CreateDirectory(text);
                }
                return Path.Combine(text, string.Format("{0}.png", DateTime.Now.ToString("MM.dd.yyyy H.mm.ss.fff")));
            }
        }

        public void Update()
        {
            if (this.ImageUri == null)
            {
                return;
            }
            try
            {
                WebRequest webRequest = WebRequest.Create(this.ImageUri);
                WebResponse response = webRequest.GetResponse();
                Image image = Image.FromStream(response.GetResponseStream());
                this.FireGotImage(image);
            }
            catch (Exception)
            {
            }
        }

        public void UpdateAndSave(int panel)
        {
            if (this.ImageUri == null)
            {
                return;
            }
            WebRequest webRequest = WebRequest.Create(this.ImageUri);
            WebResponse response = webRequest.GetResponse();
            Image image = Image.FromStream(response.GetResponseStream());
            image.Tag = panel;
            image.Save(this.ImageFilename, ImageFormat.Png);
            this.FireGotImage(image);
        }
    }
}
